import json
import traceback

from starlette.background import BackgroundTasks

from conf.config import logger
from db.task_dao import TaskDAO
from utils.originality_check import get_originality_info


class TaskService(object):
    """ 任务服务对象 """

    def __init__(self, *args, **kwargs):
        self._task_dao = TaskDAO()
        super(TaskService, self).__init__(*args, **kwargs)

    def get_task(self, task_id: int) -> dict:
        task = self._task_dao.get_task(task_id)
        return task

    def create_originality_check_task(self, content: str, chunk_size: int, k: int,
                                      total_page: int, similarity_limit: int,
                                      background_tasks: BackgroundTasks):
        task_id = self._task_dao.create_originality_check_task(content)
        background_tasks.add_task(self.originality_check, content=content, chunk_size=chunk_size, k=k,
                                  total_page=total_page, similarity_limit=similarity_limit, task_id=task_id)
        return task_id

    def originality_check(self, content: str, chunk_size: int, k: int, total_page: int, similarity_limit: int, task_id: int):
        try:
            originality_info = get_originality_info(text=content, chunk_size=chunk_size, k=k,
                                                    total_page=total_page, similarity_limit=similarity_limit)
            originality_score = originality_info.get("originality_score")
            similarity_score_ls = originality_info.get("similarity_score_ls")
            similarity_details_ls = originality_info.get("similarity_details_ls")
            self._task_dao.update_originality(originality_score=originality_score,
                                              originality_details=json.dumps(similarity_details_ls, ensure_ascii=False),
                                              task_id=task_id)
        except Exception:
            self._task_dao.update_task_status(status=3, task_id=task_id)
            error_str = traceback.format_exc()
            logger.error(error_str)


def main():
    pass


if __name__ == '__main__':
    main()
